<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center>
        <template #default>
          <van-image
            round
            class="avatar"
            :src="$store.state.userPhoto"
            @click="$refs.iptFile.click()"
          />
          <!-- file 选择框 -->
          <input
            type="file"
            ref="iptFile"
            v-show="false"
            accept="image/*"
            @change="onFileChange"
          />
        </template>
      </van-cell>
      <van-cell
        title="名称"
        :value="$store.state.userName"
        is-link
        @click="editName"
      />
      <van-cell title="生日" :value="userInfoObj?.birthday" is-link @click="editDayFn" />
    </van-cell-group>
    <!-- 修改名字弹窗 -->
    <van-dialog
      v-model="show"
      title="请小主输入新的名字 ~~"
      show-cancel-button
      :before-close="onNameDialogBeforeClose"
    >
      <van-field
        ref="focusinput"
        input-align="center"
        maxlength="7"
        placeholder="请输入名称"
        v-focus
        v-model.trim="updataName"
      />
    </van-dialog>
    <!-- 修改生日弹窗-->
    <van-popup
      v-model="isShowBirth"
      position="bottom"
      style="height: 50%"
      round
    >
      <!-- 日期选择控件 -->
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择出生日期"
        :min-date="minDate"
        :max-date="maxDate"
        :show-toolbar="true"
        @cancel="isShowBirth = false"
        @confirm="confirmFn"
      />
    </van-popup>
  </div>
</template>

<script>
import { userProfileAPI, updatePhotoAPI, updateProfileAPI } from '@/api/index'
import { Toast } from 'vant'
import Notify from '@/ui/Notify'

import { formDate } from '@/utils/day'
import { mapMutations } from 'vuex'
export default {
  name: 'UserEdit',
  data () {
    return {
      userInfoObj: {},
      show: false,
      updataName: '',
      isShowBirth: false, // 显示时间选择器
      minDate: new Date(1980, 0, 1), // 最小的可选的日期
      maxDate: new Date(), // 最大的可选日期
      currentDate: '' // 当前日期
    }
  },
  created () {
    this.getuserProfile()
  },
  mounted () {},
  methods: {
    ...mapMutations(['SET_USERPHOTO', 'SET_USERNAME']),
    // 1.0 获取用户生日
    async getuserProfile () {
      await userProfileAPI().then((res) => {
        if (res.status !== 200) return Toast.fail('获取信息出错')
        this.userInfoObj = res.data.data || {}
      })
    },
    // 2.0 修改头像
    async onFileChange (e) {
      // 加入用户没有选择，取消
      if (e.target.files[0] === undefined) return
      const fd = new FormData()
      fd.append('photo', e.target.files[0])
      await updatePhotoAPI(fd).then((res) => {
        console.log(res)
        if (res.status !== 200) return Toast.fail('更换头像失败')
        Toast.success('更换头像成功')
        this.userInfoObj.photo = res.data.data.photo || ''
        // 保存更换的头像到vuex中
        this.SET_USERPHOTO(this.userInfoObj.photo)
      })
    },
    // 3.0 修改用户名字
    editName () {
      this.show = true
      this.updataName = this.userInfoObj.name
    },
    // 3.1 修改用户名字确定按钮
    onNameDialogBeforeClose (action, done) {
      if (action === 'confirm') {
        console.log('确定')
        if (/^[A-Za-z0-9\u4e00-\u9fa5]{1,7}$/.test(this.updataName)) {
          // 通过验证,吊起接口
          this.updateProfile(this.updataName)
          done()
        } else {
          // 提示用户
          Notify({ type: 'warning', message: '用户名中英文和数字1-7位' })
          // 阻止弹窗关闭
          done(false)
        }
      } else {
        done()
      }
    },
    // 3.2 修改用户名称接口
    async updateProfile (name) {
      const res = await updateProfileAPI({ userName: name })
      if (res.status !== 200) return Toast.fail('修改失败')
      Toast.success('修改成功')
      this.userInfoObj.name = name
      this.SET_USERNAME(name)
    },
    // 4.0 修改生日
    editDayFn () {
      this.isShowBirth = true
    },
    // 4.1 修改生日确认事件
    async  confirmFn () {
      await updateProfileAPI({ birthday: formDate(this.currentDate) }).then(res => {
        if (res.status !== 200) return Toast.fail('修改生日失败')
        Toast.success('修改生日成功')
        this.isShowBirth = false
        this.userInfoObj.birthday = formDate(this.currentDate)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.user-edit-container {
  padding-top: 46px;
  .avatar {
    width: 50px;
    height: 50px;
  }
}
</style>
